const express = require('express')
const { Server } = require('socket.io')

const app = express()

// 输入输出
const io = new Server(3000, {
  // 跨域
  cors: {
    // 只要都是http://localhost:8080连接的客户端，都会被忽略
    origin: ['http://localhost:8080']
  }
})

// 表格数据
const data = [
  {
    id: 1,
    name: '张三',
    age: 18,
    score: 76 // 分数
  },
  {
    id: 2,
    name: '李四',
    age: 25,
    score: 88
  },
  {
    id: 3,
    name: '王五',
    age: 13,
    score: 54
  }
]


// 每个客户端连接都会触发的回调函数
io.on('connection', (socket) => {
  console.log('客户端连接socket服务成功！')
  socket.emit('loadData', data)

  socket.on('changeStatus', (status) => {
    io.emit('changeStatus', status)
  })

  socket.on('changeData', (userList) => {
    io.emit('changeData', userList)
  })
})

// 监听5055端口
app.listen(5055, () => {
  console.log('server running at http://127.0.0.1:5055')
})